package it.tukano.swingdeco.containers;

import java.awt.Component;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.Insets;
import java.awt.LayoutManager;

/**
 * Layout components in a vertical row
 */
public class VerticalLayout implements LayoutManager {
    
    private int margin;

    /**
     * Instance initializer
     */
    public VerticalLayout() {
    }

    public void addLayoutComponent(String name, Component comp) {
    }

    public void removeLayoutComponent(Component comp) {
    }

    public Dimension preferredLayoutSize(Container parent) {
        synchronized (parent.getTreeLock()) {
            return computePreferredLayoutSize(parent);
        }
    }

    public Dimension minimumLayoutSize(Container parent) {
        return preferredLayoutSize(parent);
    }

    public void layoutContainer(Container parent) {
        synchronized (parent.getTreeLock()) {
            doLayoutContainer(parent);
        }
    }

    /* Pre: synchronized on parent.getTreeLock */
    private Dimension computePreferredLayoutSize(Container parent) {
        Insets insets = parent.getInsets();
        Component[] components = parent.getComponents();
        Dimension size = new Dimension();
        int width = 0;
        int height = 0;
        for (int i = 0; i < components.length; i++) {
            Component component = components[i];
            Dimension preferredSize = component.getPreferredSize();
            width = Math.max(preferredSize.width, width);
            height += preferredSize.height;
        }
        width += insets.left + insets.right;
        height += insets.top + insets.bottom + components.length * margin;
        return size;
    }

    /* Pre: synchronized on parent.getTreeLock */
    private void doLayoutContainer(Container parent) {
        Insets insets = parent.getInsets();
        Dimension size = parent.getSize();
        Component[] components = parent.getComponents();
        int width = size.width - insets.left - insets.right;
        int x0 = insets.left;
        int y0 = insets.top;
        for (int i = 0; i < components.length; i++) {
            Component component = components[i];
            Dimension preferredSize = component.getPreferredSize();
            component.setBounds(x0, y0, width, preferredSize.height);
            y0 += preferredSize.height + margin;
        }
    }
}
